package com.hrbxlh.util;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.List;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.w3c.dom.Document;


/**
* -------------------------------------------------------
* Copyright (c) 2017, 鑫联华信息科技股份有限公司
* All rights reserved.
* FileName：HtmlToWord.java
* Description：文件格式转换类
* History：
* Date           Author               Desc
* 2017.9.25		  xzx                 建立
* -------------------------------------------------------
*/
public class FileConvert {
	
	/**
	 *@description htmlToWord 
	 *@param html文件的路径，带前缀
	 *@param word文件的路径，带前缀
	 * 
	 * */
	public void htmlToWord(String filePath, String destinPath) throws Exception {
        InputStream bodyIs = new FileInputStream(filePath);
        String body = this.getContent(bodyIs);
        String content = "<html><head><style></style></head><body>" + body + "</body></html>";
        InputStream is = new ByteArrayInputStream(content.getBytes("GBK"));
        OutputStream os = new FileOutputStream(destinPath);
        this.inputStreamToWord(is, os);
     }
    
     /**
      *@description 把is写入到对应的word输出流os中
      * 不考虑异常的捕获，直接抛出
      * @param is
      * @param os
      * @throws IOException
      */
     private void inputStreamToWord(InputStream is, OutputStream os) throws IOException {
        POIFSFileSystem fs = new POIFSFileSystem();
        //对应于org.apache.poi.hdf.extractor.WordDocument
        fs.createDocument(is, "WordDocument");
        fs.writeFilesystem(os);
        os.close();
        is.close();
     }
    
     /**
      *@description 把输入流里面的内容以UTF-8编码当文本取出。
      * 不考虑异常，直接抛出
      * @param ises
      * @return
      * @throws IOException
      */
     private String getContent(InputStream... ises) throws IOException {
        if (ises != null) {
           StringBuilder result = new StringBuilder();
           BufferedReader br;
           String line;
           for (InputStream is : ises) {
              br = new BufferedReader(new InputStreamReader(is, "GB2312"));
              while ((line=br.readLine()) != null) {
                  result.append(line);
              }
           }
           return result.toString();
        }
        return null;
     }
     
     /**
     * @description pdf转html
     * @param 文件前缀
     * @param 已经上传了的pdf文件名
     * @throws Exception 
     * 
      * 
      * */
     public String pdfConvertHtml(String filePath, String fileName) throws Exception{
    	 String destinName ="";
    	 //pdf文件全路径
		 String pdfpath = filePath + "/" + fileName;
		 String extArr [] = fileName.split("\\.");
		 String path = filePath + "/" + extArr[0]+".doc";
		//建立word文件
		 File saveWordFile = new File(path);
		 //建立文件夹
		 if (!saveWordFile.exists()) {
			 File saveWordFileDir = new File(path.substring(0,path.lastIndexOf("\\") + 1));
			 saveWordFileDir.mkdirs();
			 saveWordFile = new File(path);
		 }
		 String fileWord = String.valueOf(saveWordFile);
		 //将pdf转为word
		 FileUpload fileUpload = new FileUpload();
		 File filePdf = new File(pdfpath);
		 fileUpload.readPdf(String.valueOf(filePdf), fileWord);
		 //将word转为html
		 wordConvertHtml(filePath, extArr[0]+".doc", extArr[0]+".html");
    	 //删除刚才的word文件
		 fileUpload.deleteFileOnly(filePath, extArr[0]+".doc");
		 destinName = extArr[0]+".html";
    	 return destinName;
     }
     
     /***
 	 * @description 将word转换为html
 	 * @param 前缀路径 有/
 	 * @param word文件的名字
 	 * @param html文件的名字
 	 * 
 	 * */
 	public void wordConvertHtml(String filePath, String fileName, String destinName) throws IOException, ParserConfigurationException, TransformerException{
         InputStream input = new FileInputStream (filePath + fileName);
         HWPFDocument wordDocument = new HWPFDocument (input);
         WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter (DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument() );
         wordToHtmlConverter.setPicturesManager (new PicturesManager() {
             public String savePicture (byte[] content, PictureType pictureType, String suggestedName, float widthInches, float heightInches) {
                 return suggestedName;
             }
         });
         wordToHtmlConverter.processDocument (wordDocument);
         List pics = wordDocument.getPicturesTable().getAllPictures();
         if (pics != null) {
             for (int i = 0; i < pics.size(); i++) {
                 Picture pic = (Picture) pics.get (i);
                 try {
                     pic.writeImageContent (new FileOutputStream (filePath + pic.suggestFullFileName() ) );
                 } catch (FileNotFoundException e) {
                     e.printStackTrace();
                 }
             }
         }
         Document htmlDocument = wordToHtmlConverter.getDocument();
         ByteArrayOutputStream outStream = new ByteArrayOutputStream();
         DOMSource domSource = new DOMSource (htmlDocument);
         StreamResult streamResult = new StreamResult (outStream);
  
         TransformerFactory tf = TransformerFactory.newInstance();
         Transformer serializer = tf.newTransformer();
         serializer.setOutputProperty (OutputKeys.ENCODING, "utf-8");
         serializer.setOutputProperty (OutputKeys.INDENT, "yes");
         serializer.setOutputProperty (OutputKeys.METHOD, "html");
         serializer.transform (domSource, streamResult);
         outStream.close();
         String content = new String (outStream.toByteArray() );
         FileUtils.write (new File (filePath, destinName), content, "utf-8");
 	}
 	
 	
     
     public static void main(String[] args) throws Exception {
    	 FileConvert t = new FileConvert();
		t.htmlToWord("e://11111.html","e://11111.doc");

	}
     
}
